import styles from './index.module.scss'
import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import { useDispatch, useSelector } from 'react-redux'
import { useEffect, useRef, useState } from 'react'
import { useParams } from 'react-router-dom'
import { getArticleDetails, getCommentList } from '@/store/action/article'
import { RootState } from '@/store'
import DOMPurify from 'dompurify'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { InfiniteScroll, Skeleton } from 'antd-mobile'
import highlight from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import ArticleFooter from './components/ArticleFooter'
import NoComment from './components/NoComment'
import CommentItem from './components/CommentItem'

export default function Article() {

  const dispatch = useDispatch()

  const { id } = useParams<{ id: string }>()


  // 进页面滚动到顶部
  useEffect(() => {
    window.scrollTo({ top: 0 })
  }, [dispatch])

  useEffect(() => {
    // 通过id获取文章详情
    dispatch(getArticleDetails(id))
    // 通过id获取评论列表
    dispatch(getCommentList({ type: 'a', source: id }))
    return () => {
      dispatch({ type: 'article/getInfo', payload: {} })

      // 卸载组件的时候清理评论列表
      dispatch({ type: 'article/clearCommentList' })

    }
  }, [id, dispatch])

  // 从仓库获取所有的评论列表
  const { commentList } = useSelector((state: RootState) => state.article)
  const { results, end_id, last_id } = commentList
  // 无限滚动
  const loadMore = async () => {
    await dispatch(getCommentList({ type: 'a', source: id, offset: last_id }))
  }

  const { info } = useSelector((state: RootState) => state.article)


  const [showAuthor, setShowAuthor] = useState(false)

  const authorRef = useRef<HTMLDivElement>(null)

  const scrollFu = () => {
    const { top } = authorRef.current!.getBoundingClientRect()

    if (top < 0) setShowAuthor(true)
    else setShowAuthor(false)
  }




  useEffect(() => {
    if (!info.art_id) return
    // 代码片段高亮
    highlight.configure({
      // 忽略未经转译的 HTML 字符
      ignoreUnescapedHTML: true
    })
    // code 标签 pre 标签 ，dg-html类型，是内容里面后台返回的格式

    // 优先给code标签加上类名-因为code是pre的子标签
    const code = document.querySelectorAll('.dg-html pre code')
    if (code.length) code.forEach(el => highlight.highlightElement(el as any))
    // 可能只有pre标签 没有code标签
    const pre = document.querySelectorAll('.dg-html pre')
    if (pre.length) pre.forEach(el => highlight.highlightElement(el as any))


    // 监听滚动
    window.addEventListener('scroll', scrollFu, true)
    return () => {
      window.removeEventListener('scroll', scrollFu, true)
    }

    // 在有数据之后在渲染 代码片段
  }, [info.art_id])



  return (
    <div className={styles.root}>
      <div className='root-wrapper'>
        {/* 顶部导航栏 */}
        <NavBar fixed={true} right={<Icon type='icongengduo' />}>
          <div className='nav-author' hidden={!showAuthor}>
            <img src={info.aut_photo} alt='' />
            <span className='name'>{info.aut_name}</span>
            <span className='follow'>关注</span>
          </div>
          <div hidden={showAuthor}>文章详情</div>
        </NavBar>

        {/* 骨架屏 */}
        {info.art_id ?
          (<div className='wrapper'>
            <div className='article-wrapper'>
              {/* 文章描述信息栏 */}
              <div className='header'>
                <h1 className='title'>{info.title}</h1>

                <div className='info'>
                  <span>{dayjs(info.pubdate).format('YYYY-MM-DD HH:mm:ss')}</span>
                  <span>{info.read_count} 阅读</span>
                  <span>{info.comm_count} 评论</span>
                </div>

                <div className='author' ref={authorRef}>
                  <img src={info.aut_photo} alt='' />
                  <span className='name'>{info.aut_name}</span>
                  <span className={classNames(info.is_followed ? 'follow' : '')}>{info.is_followed ? '' : '已'}关注</span>
                </div>
              </div>

              {/* 文章正文内容区域 */}
              <div className='content'>
                <div className='content-html dg-html' dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(info.content) }}></div>
                <div className='date'>发布文章时间：{dayjs().from(info.pubdate)}</div>
              </div>
            </div>
          </div>)
          :
          (<div style={{ padding: '0 16px' }}>
            <Skeleton.Title animated />
            <Skeleton.Paragraph lineCount={15} animated />
          </div>)}

        <div className='divider'></div>
        <div className='comment'>
          {/* 评论总览信息 */}
          <div className='comment-header'>
            <span>全部评论（{info.comm_count}）</span>
            <span>{info.like_count} 点赞</span>
          </div>
          {/* 评论列表 */}
          {info.comm_count === 0 ? <NoComment /> : (

            results && results.length ?
              results.map((item) => (
                < CommentItem key={item.aut_id} comment={item} />
              ))
              :
              <></>
          )}
          {results && results.length && <InfiniteScroll loadMore={loadMore} hasMore={end_id !== last_id} />}

        </div>
        {/* 文章底部 */}
        <ArticleFooter />
      </div>
    </div>
  )
}